<template>
  <div>
    <div class="row-header" :style="{'overflow-x': $store.state.app.screenWidth<590?'scroll':'none'}">
      <el-form label-width="50px" :inline="true" :style="{'width': $store.state.app.screenWidth<520?'520px':'99%'}">
        <el-form-item label=" ">
          <el-autocomplete class="inline-input" size="small" v-model="search.userName" style="width: 300px;"
                           :fetch-suggestions="querySearch" :trigger-on-focus="false" @select="handleSelect"
                           placeholder="请输入代理名称"></el-autocomplete>
        </el-form-item>
        <el-form-item label=" " prop="phone">
          <el-select v-model="search.dictTransactionType" style="width: 300px">
            <el-option label="请选择变动类型" value=""></el-option>
            <el-option label="提现" value="RETURNMONEY"></el-option>
            <el-option label="后台充值" value="RECHARGE"></el-option>
            <el-option label="自助充值" value="RECHARGE_BY_SELF"></el-option>
            <el-option label="自动提现" value="AUTORETURN"></el-option>
            <el-option label="充值扣款" value="WITHHOLD"></el-option>
            <el-option label="批量充值" value="BATCH_RECHARGE"></el-option>
            <el-option label="三方下单扣款" value="THIRD_ORDER"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label=" " prop="address">
          <el-input placeholder="请输入业务号码" size="small" v-model.trim="search.cardNumber" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label=" " prop="address">
          <el-select v-model="search.dictMethod" style="width: 300px;">
            <el-option label="请选择变动对象" value=""></el-option>
            <el-option label="微信" value="WX"></el-option>
            <el-option label="支付宝" value="ZFB"></el-option>
            <el-option label="余额" value="YE"></el-option>
            <el-option label="其他" value="TRANS_OTHER"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label=" " prop="contacts">
          <el-date-picker
            v-model="search.transactionRecord"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="交易开始日期"
            end-placeholder="交易结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
          <el-form-item label="列表最大条数:" label-width="150px"  prop="maxCount">
            <el-input v-model="search.maxCount" placeholder="列表最大条数" type="number" min="10" max="5000" ></el-input>
          </el-form-item>
        </el-form-item>
      </el-form>
      <div class="row-form-btn">
        <el-button size="small" type="shenda" icon="el-icon-search" :loading="searchLoading" @click="currentPage = 1 ; searchHandle()">查询</el-button>
        <el-button size="small" type="shenda" icon="el-icon-refresh-right" @click="clearForm()">重置</el-button>
        <el-button size="small" type="shenda" icon="el-icon-download" @click="exlDownload" :loading="loading">导出</el-button>
      </div>
<!--      <el-form :model="ruleForm" ref="ruleForm" v-if="checkPer('repeatFyPer')" label-width="50px">-->
<!--        <el-form-item label=" " prop="searchTime" :rules="[{required: true, message: '请选择返佣时间'}]">-->
<!--          <el-date-picker v-model="ruleForm.searchTime" type="date" placeholder="请选择返佣时间"></el-date-picker>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <div class="row-form-btn" v-if="checkPer('repeatFyPer')">-->
<!--        <el-button size="small" type="shenda" icon="el-icon-search" :loading="searchLoading" @click="selectRepeatRecord('ruleForm')">查询重复返佣</el-button>-->
<!--        <el-button size="small" type="shenda" icon="el-icon-refresh-right" @click="resetRuleForm('ruleForm')">重置重复返佣</el-button>-->
<!--      </div>-->
    </div>
    <div class="split-line"></div>
    <div class="row-main">
      <el-button type="shenda" round size="small"><b>资金变动总额：</b><span class='btn_text'>{{ sumTransactionMoney }}</span> <b>元</b></el-button>
      <el-table :header-cell-style="{ 'background':$store.state.app.tableBgColor,'color':'#606266' }" :data=" tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)" tooltip-effect="dark"
                class="row-main-table"
                @selection-change="handleSelectionChange" v-loading.fullscreen="tableLoading"
                element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.2)" ref="table">
        <el-table-column prop="loginName" label="代理账号" align="center" :fixed="$store.state.app.screenWidth<992?true:false" :width="$store.state.app.screenWidth<992?'150px':'auto'"></el-table-column>
        <el-table-column prop="cardNumber" label="业务号码" align="center" :width="$store.state.app.screenWidth<992?'180px':'auto'"></el-table-column>
        <el-table-column prop="setMealName" label="套餐名称" align="center" :width="$store.state.app.screenWidth<992?'130px':'auto'"></el-table-column>
        <el-table-column prop="dictTransactionTypeName" label="交易类型" align="center" :width="$store.state.app.screenWidth<992?'130px':'auto'"></el-table-column>
        <el-table-column prop="dictMethodName" label="资金变动对象" align="center" :width="$store.state.app.screenWidth<992?'130px':'auto'"></el-table-column>
        <el-table-column prop="beforBalance" label="变动前金额" align="center" :width="$store.state.app.screenWidth<992?'130px':'auto'"></el-table-column>
        <el-table-column prop="transactionMoney" label="本次变动金额" align="center" :width="$store.state.app.screenWidth<992?'130px':'auto'"></el-table-column>
        <el-table-column prop="afterBalance" label="变动后金额" align="center" :width="$store.state.app.screenWidth<992?'130px':'auto'"></el-table-column>
        <el-table-column prop="customerOrderNumber" label="订单号" align="center" :width="$store.state.app.screenWidth<992?'130px':'auto'"></el-table-column>
        <el-table-column prop="insertTimeTime" label="变动时间" align="center" :width="$store.state.app.screenWidth<992?'180px':'auto'"></el-table-column>
        <el-table-column prop="remark" label="备注" align="center" :width="$store.state.app.screenWidth<992?'180px':'auto'"></el-table-column>
      </el-table>
      <div :style="{'overflow-x': $store.state.app.screenWidth<992?'scroll':'none'}">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="currentPage" :page-size="pageSize" class="row-main-pager"
                     layout="total, sizes, prev, pager, next, jumper" :total="totalPage"
                     :page-sizes="[10,20,50,100]" background></el-pagination>
      </div>
      <el-dialog class="delete" top="33vh" :visible.sync="showRemoveReap" :append-to-body="true" width="30%">
        <el-button type="primary" size="small" style="margin-bottom:20px" @click="removeReapRecords()"
                   :disabled="tableData1==''">去除重复返佣
        </el-button>
        <el-table height="300" border :header-cell-style="{ 'background':$store.state.app.tableBgColor,'color':'#606266' }" :data="tableData1"
                  tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange"
                  v-loading.fullscreen="tableLoading" element-loading-text="拼命加载中"
                  element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.2)">
          <el-table-column prop="agentName" label="代理" align="center"></el-table-column>
          <el-table-column prop="cardNumber" label="业务号码" align="center"></el-table-column>
          <el-table-column prop="mealName" label="套餐名字" align="center"></el-table-column>
          <el-table-column prop="transactionMoney" label="交易金额" align="center"></el-table-column>
          <el-table-column prop="insertTime" label="返佣时间" align="center"></el-table-column>
        </el-table>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {selectTransactionRecord, selectRepeatRecord, removeReapRecords, getLoginName,downloadTransactionRecord,sumTransactionRecord} from '@/api/getData'

export default {
  name: "oemListIndex",
  data() {
    return {
      loading: false,
      tableLoading: false,
      showRemoveReap: false,
      sumTransactionMoney: null,//资金变动总额
      ruleForm: {
        name: 'searchTime',
      },
      rules: {
        searchTime: [
          {type: 'date', required: true, message: '请选择日期', trigger: 'change'}
        ],
        maxCount:[
          { type: 'number', message: '必须为数字'},
          { required: true, message: '不能为空'}
        ]
      },
      search: {
        transactionRecord: [],
        userName: '',
        dictTransactionType: '',
        cardNumber: '',
        dictMethod: '',
        maxCount:500
      },
      value1: '',
      pageSize: 10,
      currentPage: 1,
      ascs: [],
      descs: [],
      maxPage: 1,
      tableData: [],
      tableData1: [],
      searchLoading: false,
      totalPage: 0,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      color: ''
    }
  },
  created() {
    this.color = document.body.style.getPropertyValue('--normalBg').trim();
    this.initData()
  },
  methods: {
    //查询重复返佣
    async selectRepeatRecord(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.showRemoveReap = true
          this.removeReapRecords1()
        } else {
          return false;
        }
      });

    },

    async querySearch(queryString, cb) {
      let a = await getLoginName({
        loginname: this.search.userName
      })
      if (a._result) {
        this.loginNames = [];
        for (let i = 0; i < a.data.length; i++) {
          this.loginNames.push({'value': a.data[i]})
        }
      }

      var loginNames = this.loginNames;
      //var results = queryString ? loginNames.filter(this.createFilter(queryString)) : loginNames;
      // 调用 callback 返回建议列表的数据
      cb(loginNames);
    },
    async removeReapRecords1() {
      this.tableLoading = true;
      const returnData = await selectRepeatRecord({
          searchTime: this.ruleForm.searchTime.format("yyyy-MM-dd"),
        },
        {
          obj: this,
          key: 'tableLoading'
        })
      this.tableData1 = []
      if (returnData._result) {
        // 数据回显
        returnData.data.map(item => {
          const obj = {}
          obj.agentName = item.agentName
          obj.cardNumber = item.cardNumber
          obj.mealName = item.mealName
          obj.beforBalance = item.beforBalance
          obj.transactionMoney = item.transactionMoney
          obj.insertTime = item.insertTime
          this.tableData1.push(obj)
        })
        this.tableLoading = false
      }
    },
    //去除重复返佣
    async removeReapRecords() {
      let s = await removeReapRecords({
        searchTime: this.ruleForm.searchTime.format("yyyy-MM-dd"),
      })
      if (s._result) {
        this.$message.success("操作成功！")
        this.showRemoveReap = false
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val
      //this.initData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
     // this.initData()
    },
    searchHandle() {
      this.initData('searchLoading')
    },
    handleSelect() {

    },
    resetRuleForm(formName) {
      this.$refs[formName].resetFields();
    },
    exlDownload() {
      downloadTransactionRecord({
        dictTransactionType: this.search.dictTransactionType,
        dictMethod: this.search.dictMethod,
        userName: this.search.userName,
        cardNumber: this.search.cardNumber,
        startDate: this.search.transactionRecord[0],
        endDate: this.search.transactionRecord[1],
      })
      this.$confirm('正在查询中，是否立即前往任务中心查看结果?', '提示', {
        confirmButtonText: '前往任务中心',
        cancelButtonText: '留在当前页',
        type: 'warning'
      }).then(() => {
        this.$router.push({
          path: '/mission/mission'
        })
      }).catch(() => {

      });
    },
    async initData(theKey) {
      this.tableLoading = true;
      this.sumTransactionMoney = null;
      const returnData = await
        selectTransactionRecord({
          dictTransactionType: this.search.dictTransactionType,
          dictMethod: this.search.dictMethod,
          userName: this.search.userName,
          cardNumber: this.search.cardNumber,
          startDate: this.search.transactionRecord[0],
          endDate: this.search.transactionRecord[1],
          maxCount:this.search.maxCount,
          page: {
            current: this.currentPage + '',
            size: this.pageSize + '',
            ascs: this.ascs,
            descs: this.descs
          }
        }, {
          obj: this,
          key: 'tableLoading;' + theKey
        })
      this.tableData = [];
      this.totalPage = 0;
      if (returnData._result) {
        // this.maxPage = Math.ceil(returnData.data.total / this.pageSize) // 分页的最大页数
        this.totalPage = returnData.data.length;
        // 数据回显
        returnData.data.map(item => {
          const obj = {}
          obj.userId = item.userId
          obj.dictTransactionTypeName = item.dictTransactionTypeName
          obj.dictMethodName = item.dictMethodName
          obj.beforBalance = item.beforBalance
          obj.transactionMoney = item.transactionMoney
          obj.remark = item.remark
          obj.afterBalance = item.afterBalance
          obj.insertUser = item.insertUser
          obj.insertUserName = item.insertUserName
          obj.userName = item.userName
          obj.startDate = item.startDate
          obj.endDate = item.endDate
          obj.customerOrderId = item.customerOrderId
          obj.cardNumber = item.cardNumber
          obj.customerOrderNumber = item.customerOrderNumber
          obj.setMealName = item.setMealName
          obj.insertTimeTime = item.insertTimeTime
          obj.loginName = item.loginName
          this.tableData.push(obj)
        })

        let res =  sumTransactionRecord({
          dictTransactionType: this.search.dictTransactionType,
          dictMethod: this.search.dictMethod,
          userName: this.search.userName,
          cardNumber: this.search.cardNumber,
          startDate: this.search.transactionRecord[0],
          endDate: this.search.transactionRecord[1],
          maxCount:this.search.maxCount,
        }).then(res=>{
          if(res.data){
            this.sumTransactionMoney = res.data.sumTransactionMoney
          }
        })

      }
      this.tableLoading = false
      this.searchLoading = false
    },
    clearForm() {
      this.search.transactionRecord = '';
      this.search.userName = '';
      this.search.dictTransactionType = '';
      this.search.cardNumber = '';
      this.search.dictMethod = '';
    }
    ,
  }

}
</script>

<style scoped lang="scss">
.block {
  float: right;
  position: relative;
  margin-top: 20px;
}
.btn_text_none {
  color: #c02122;
  padding: 0 5px;
}
</style>
